package com.zhongying.jf.util;

import com.zhongying.jf.ResConstants;
import com.zhongying.jf.cache.Jiucache;
import com.zhongying.jf.exception.ZhongyingiException;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;

/**
 * Created by liyuxuan on 2016/6/22.
 */
@Service
public class GetNid {

    @Autowired
    private Jiucache jiucache;

    //投资
    public final static Integer BIZ_TYPE_INVEST = 1;
    //活期投资
    public final static Integer BIZ_TYPE_DEMAND_INVEST = 2;
    //活期投资
    public final static Integer BIZ_TYPE_EXPERIENCE_INVEST = 3;

    /**
     * 生成Nid  业务名-yyyyMMddHHmmssfff+随机3位数+用户名
     * @param userId
     * @param bizType
     * @return
     */
    public String generateNid(Integer userId,Integer bizType){

        StringBuffer sb = new StringBuffer();
        sb.append(getType(bizType));
        DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyyMMddHHmmssSSS");
        String s = new DateTime().toString(dtf);
        sb.append(s);
        int i = new Random().nextInt(1000);
        sb.append(i);
        sb.append(userId);

        String nid = sb.toString();

        //存储30分钟
        jiucache.put(nid,userId,30);
        return nid;
    }

    /**
     * 获取nid
     * @param key
     * @return
     */
    public String getNid(String key){
        return jiucache.get(key).toString();
    }

    private String getType(Integer type){
        String t = null;
        switch (type){
            case 1:
                t = "TZ-";
                break;
            case 2:
                t = "HQTZ-";
                break;
            case 3:
                t = "TYTZ-";
                break;
            default:
                throw new ZhongyingiException(ResConstants.PARAM_NOT_RIGHT.getCode(),"bizType不合法");
        }
        return t;
    }
}
